package com.yonyou.pmclouds.completedcollate.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.entity.PageObject;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.IllegalRequestArgException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.completedcollate.entity.CollatedSearchPageVO;
import com.yonyou.pmclouds.completedcollate.entity.CollatedSearchParamVO;
import com.yonyou.pmclouds.completedcollate.entity.CompletedCollateVO;
import com.yonyou.pmclouds.completedcollate.rmiitf.CompletedCollateMaintain;
import com.yonyou.pmclouds.completedcollate.rmiitf.CompletedCollateQuery;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseInfo;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.outter.user.UserOperator;
import com.yonyou.pmclouds.project.entity.ProjectRefVO;
import com.yonyou.pmclouds.team.rmiitf.ProjectRefWithTeamQuery;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;

/**
 * 竣工资料整理控制器
 *
 * @author yzx
 * @Date: 2018/5/24 14:36
 */
@RestController
@RequestMapping("/completedCollate")
public class CompletedCollateController {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private CompletedCollateMaintain maintain;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private CompletedCollateQuery query;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectRefWithTeamQuery projectRefWithTeamQuery;
    @Autowired
    private EnterpriseInfoQuery constructionunitQuery;
    @Autowired
    private UserInfoQuery userQuery;
    @Autowired
    private UserOperator userOperator;

    // 创建人
    private static final String[] USER_ID_FIELDS = {CommonFieldConst.CREATOR};
    private static final String[] USER_NAME_FIELDS = {CommonFieldConst.CREATOR_NAME};
    // 创建人&接收人
    private static final String[] USER_ACCEPTOR_ID_FIELDS = {CommonFieldConst.CREATOR, CollatedSearchPageVO.ACCEPTOR};
    private static final String[] USER_ACCEPTOR_NAME_FIELDS = {CommonFieldConst.CREATOR_NAME, CollatedSearchPageVO.ACCEPTOR_NAME};


    /**
     * 根据条件查询
     *
     * @param condition 可以用空格分割成多个条件
     * @param start     开始的页码
     * @param size      每页条数
     * @return
     * @throws BusinessException
     */
    @RequestMapping(value = "/search")
    public PageObject search(@RequestParam(name = "pkTenant") String pkTenant,
                             @RequestParam(required = false) String condition,
                             @RequestParam(required = false) Integer start,
                             @RequestParam(required = false) Integer size) throws BusinessException, IOException {

        //获取组织权限及项目团队下所有项目
        Map map = userOperator.queryRoleByUserId(pkTenant, RuntimeEnvironment.getLoginUserId());
        List<String> pkRoles = new ArrayList<>();
        if (map != null && map.get("data") != null) pkRoles = (ArrayList) map.get("data");
        PageObject<ProjectRefVO> projectPage = projectRefWithTeamQuery.queryOfUser(RuntimeEnvironment.getLoginUserId(), pkTenant, null,
                Integer.valueOf(0), Integer.valueOf(1000), pkRoles.toArray(new String[0]));
        if(projectPage == null || ArrayUtils.isEmpty(projectPage.getObjects()))
            return new PageObject(new CompletedCollateVO[0], 0, 0);

        String[] pkProjects = new String[0];
        Object[] obs = projectPage.getObjects();
        for(Object refVO : obs){
            pkProjects = ArrayUtils.add(pkProjects, ((ProjectRefVO) refVO).getPkProject());
        }

        PageObject pageObject = query.search(pkProjects, condition, start, size);
        // 为创建人赋值&项目经理
        userQuery.tranUserInfoField(pageObject.getObjects(), new String[]{CommonFieldConst.CREATOR, CompletedCollateVO.MANAGER},
                new String[]{CommonFieldConst.CREATOR_NAME, CompletedCollateVO.MANAGER_NAME});
        return pageObject;
    }

    @PostMapping("/insertOrUpdate")
    public CompletedCollateVO insertOrUpdate(@RequestBody @Validated CompletedCollateVO collateVO, BindingResult errors) throws BusinessException {
        if (errors.hasErrors()) {
            throw new IllegalRequestArgException();
        }
        collateVO.setPkTenant(RuntimeEnvironment.getTenantId());
        // 主键为空表示新增
        String id;
        if (StringUtils.isEmpty(collateVO.getPkCompletedCollate())) {
            id = maintain.insert(collateVO);
        } else {
            id = maintain.update(collateVO);
        }
        CompletedCollateVO resultVO = query.getById(id);
        // 为创建人赋值
        userQuery.tranUserInfoField(new CompletedCollateVO[]{resultVO}, USER_ID_FIELDS, USER_NAME_FIELDS);
        return resultVO;
    }

    @GetMapping("/queryOne")
    public CompletedCollateVO queryOne(@RequestParam String pkCompletedCollate) throws BusinessException {
        CompletedCollateVO resultVO = query.getById(pkCompletedCollate);
        // 为创建人赋值
        userQuery.tranUserInfoField(new CompletedCollateVO[]{resultVO}, USER_ID_FIELDS, USER_NAME_FIELDS);
        return resultVO;
    }

    @PostMapping("/delete")
    public void delete(@RequestBody CompletedCollateVO collateVO) throws BusinessException {
        if (StringUtils.isEmpty(collateVO.getPkCompletedCatalog()) || StringUtils.isEmpty(collateVO.getChangeFlag())) {
            throw new IllegalRequestArgException();
        }
        maintain.deleteCollate(collateVO);
    }

    @PostMapping("/searchBillsInfo")
    public List<CollatedSearchPageVO> searchBillsInfo(@RequestBody CollatedSearchParamVO paramVO) throws BusinessException {
        List<CollatedSearchPageVO> pageVOList = query.getBillsInfo(paramVO);
        // 为创建人赋值
        userQuery.tranUserInfoField(pageVOList.toArray(new CollatedSearchPageVO[pageVOList.size()]), USER_ACCEPTOR_ID_FIELDS, USER_ACCEPTOR_NAME_FIELDS);
        // 施工单位
        for (CollatedSearchPageVO collatedSearchPageVO : pageVOList) {
            if (!StringUtils.isEmpty(collatedSearchPageVO.getConstruction())) {
                String pk_constructionunit = collatedSearchPageVO.getConstruction();
                EnterpriseInfo enterpriseInfo = constructionunitQuery.queryEnterpriseById(pk_constructionunit);
                collatedSearchPageVO.setConstructionName(enterpriseInfo.getName());
            }
        }
        return pageVOList;
    }
}
